package com.alphacsp.android;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Environment;
import android.preference.PreferenceManager;
import android.view.Menu;
import android.view.View;
import android.widget.ImageView;

import java.io.File;

/**
 * @author Yoav Aharoni
 */
public class ShowdownActivity extends Activity {
	private FighterView fighter1;
	private FighterView fighter2;
	private SharedPreferences preferences;

	/**
	 * Called when the activity is first created.
	 */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_showdown);

		// init fighter1
		fighter1 = new FighterView(R.id.fighter1, true, this);
		fighter1.setName(getString(R.string.defaultFighterName1));
		fighter1.getImageView().setImageResource(R.drawable.fighter1);
		fighter1.getImageView().setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				throwPunch(fighter1, fighter2);
			}
		});

		// init fighter2
		fighter2 = new FighterView(R.id.fighter2, false, this);
		fighter2.setName(getString(R.string.defaultFighterName2));
		fighter2.getImageView().setImageResource(R.drawable.fighter2);
		fighter2.getImageView().setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				throwPunch(fighter2, fighter1);
			}
		});

		// init newFight button
		findViewById(R.id.newFight).setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				startNewFight();
			}
		});
		// init autoFight button
		findViewById(R.id.autoFight).setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				startAutoFight();
			}
		});

		// init settings button
		findViewById(R.id.settings).setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				showSettings();
			}
		});

		// init about button
		findViewById(R.id.about).setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				showAboutDialog();
			}
		});		// init about button
		findViewById(R.id.about).setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				showAboutDialog();
			}
		});

		// init local storage (key/value preferences)
		preferences = PreferenceManager.getDefaultSharedPreferences(this);
	}

	private void throwPunch(FighterView hitter, FighterView hitted) {
		hitter.punch();
		hitted.takeHit();
		checkFightStatus();
	}

	private void startNewFight() {
		fighter1.setPower(100);
		fighter2.setPower(100);
		checkFightStatus();
	}

	private void checkFightStatus() {
		if (fighter1.getPower() == 0) {
			fighterWon(fighter2);
		} else if (fighter2.getPower() == 0) {
			fighterWon(fighter1);
		}
	}

	private void startAutoFight() {
		new Thread() {
			@Override
			public void run() {
				while (fighter2.getPower() > 0 && fighter1.getPower() > 0) {
					runOnUiThread(new Runnable() {
						public void run() {
							if (Math.random() > 0.5) {
								throwPunch(fighter1, fighter2);
							} else {
								throwPunch(fighter2, fighter1);
							}
						}
					});

					try {
						sleep(1000);
					} catch (InterruptedException ignored) {
						return;
					}
				}
			}
		}.start();
	}

	@Override
	protected void onPause() {
		super.onPause();

		// save score
		preferences.edit()
				.putInt("fighterScore1", fighter1.getPower())
				.putInt("fighterScore2", fighter2.getPower())
				.commit();
	}

	@Override
	public boolean onPrepareOptionsMenu(Menu menu) {
		showSettings();
		return false;
	}

	@Override
	protected void onResume() {
		super.onResume();

		// load saved fighter #1 data
		fighter1.setPower(preferences.getInt("fighterScore1", 100));
		fighter1.setName(preferences.getString("fighterName1", getString(R.string.defaultFighterName1)));
		loadImage(fighter1, "fighterImage1", R.drawable.fighter1);

		// load saved fighter #2 data
		fighter2.setPower(preferences.getInt("fighterScore2", 100));
		fighter2.setName(preferences.getString("fighterName2", getString(R.string.defaultFighterName2)));
		loadImage(fighter2, "fighterImage2", R.drawable.fighter2);
	}

	private void showSettings() {
		startActivity(new Intent(this, SetupActivity.class)
				.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET));
	}

	private void fighterWon(FighterView winner) {
		// setup custom dialog view
		final View dialogView = getLayoutInflater().inflate(R.layout.dialog_fight_over, null);
		final ImageView winnerImage = (ImageView) dialogView.findViewById(R.id.winnerImage);
		winnerImage.setImageDrawable(winner.getImageView().getDrawable());

		// create dialog
		final AlertDialog dialog = new AlertDialog.Builder(this)
				.setTitle(winner.getName() + " Wins!")
				.setView(dialogView)
				.setPositiveButton(R.string.close, null)
				.setCancelable(true)
				.create();

		// start new fight on close
		dialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
			public void onDismiss(DialogInterface dialog) {
				startNewFight();
			}
		});

		dialog.show();
	}

	private void showAboutDialog() {
		new AlertDialog.Builder(this)
				.setTitle(getString(R.string.aboutTitle))
				.setMessage(getString(R.string.aboutMessage))
				.setPositiveButton(R.string.close, null)
				.setCancelable(true)
				.show();
	}

	private void loadImage(FighterView fighterView, String imagePref, int defaultImage) {
		final boolean customImage = preferences.getBoolean(imagePref, false);
		if (customImage) {
			final File photoFile = new File(Environment.getExternalStorageDirectory(), imagePref);
			Bitmap photo = BitmapFactory.decodeFile(photoFile.getAbsolutePath());
			photo = compressImage(photo);
			fighterView.getImageView().setImageBitmap(photo);
		} else {
			fighterView.getImageView().setImageResource(defaultImage);
		}
	}

	public static Bitmap compressImage(Bitmap photo) {
		//shrink image:
		int origH = photo.getHeight();
		int origW = photo.getWidth();
		int maxScale = Math.max(origH / 600, origW / 600);
		if (maxScale > 1) {
			photo = Bitmap.createScaledBitmap(photo, origW / maxScale, origH / maxScale, false);
		}
		return photo;
	}
}

